#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include "../Includes/Driver.h"
#include "../Includes/Rendering.h"
#include "../Includes/Messaging.h"
#include <linux/input.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <fcntl.h>

/// <summary>
/// Macros
/// </summary>
#define NUM_EVENTS 128
#define ABS_UNSET -65535
#define BITS_PER_LONG (sizeof(long) * 8)
#define NBITS(x) ((((x)-1)/BITS_PER_LONG)+1)
#define ISBITSET(x,y) ((x)[LONG(y)] & BIT(y))
#define OFF(x) ((x)%BITS_PER_LONG)
#define LONG(x) ((x)/BITS_PER_LONG)
#define BIT(x) (1 << OFF(x))

/// <summary>
/// Mouse Locals
/// Generic Mouse Driver
/// </summary>
int dev_handle;
pthread_t m_thread;
pthread_mutex_t m_lock;

/// <summary>
/// Device Map
/// </summary>
const char *devices[6] =
{
	"/dev/input/mice",
	"/dev/input/mouse0",
	"/dev/input/event0",
	"/dev/input/event1",
	"/dev/input/event2",
	"/dev/input/event3"
};

/// <summary>
/// TODO
/// </summary>
int inline MOUIsMouse(int handle)
{
	return handle;
}

/// <summary>
/// TODO
/// </summary>
int inline MOUFind()
{
	int i = 0;
	int handle = -1;
	for (i = 0; i < 6; i++) {
		if ((handle = open(devices[i], O_RDWR)) < 0)
			continue;
		if (MOUIsMouse(handle) > 0)
			return handle;
		close(handle);
	}
	return -1;
}

/// <summary>
/// TODO
/// </summary>
int MOUInit()
{
	if ((dev_handle = MOUFind()) < 0)
		return -1;

	if (pthread_create(&m_thread, NULL, MOUThread, NULL) != 0)
		return -2;

	return 0;
}

/// <summary>
/// TODO
/// </summary>
void* MOUThread(void* arg)
{
	for (;;) {
	}
	return 0;
}

/// <summary>
/// TODO
/// </summary>
int MOUExit()
{
	if (pthread_cancel(m_thread) != 0)
		return -1;
	close(dev_handle);		
	return 0;
}
